﻿using System;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using umbraco.presentation.nodeFactory;

namespace CultivContactForm
{
    public partial class CultivContactForm : UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            //Disable ValidateRequest so that snippets of HTML can be sent
            ((umbraco.UmbracoDefault)Page).ValidateRequest = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetTextValues();
        }

        protected void contactSubmitButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SendContactMail();
                DoRedirect();
            }
            else
            {
                _recaptchaErrorLabel.Visible = true;
            }
        }

        private void SetTextValues()
        {
            _nameLabel.Text = GetPropertyFromAlias("contactNameLabel");
            _emailLabel.Text = GetPropertyFromAlias("contactEmailLabel");
            _messageLabel.Text = GetPropertyFromAlias("contactMessageLabel");
            _contactSubmitButton.Text = GetPropertyFromAlias("contactSubmitButtonLabel");

            _rfvContactEmail.ErrorMessage = GetPropertyFromAlias("contactErrorEmailBlank");
            _revContactEmail.ErrorMessage = GetPropertyFromAlias("contactErrorEmailInvalid");
            _rfvContactMessage.ErrorMessage = GetPropertyFromAlias("contactErrorMessageBlank");

            _recaptchaLabel.Text = GetPropertyFromAlias("recaptchaLabel");
            _recaptchaErrorLabel.Text = GetPropertyFromAlias("recaptchaErrorLabel");
            _recaptcha.PublicKey = GetPropertyFromAlias("recaptchaPublicKey");
            _recaptcha.PrivateKey = GetPropertyFromAlias("recaptchaPrivateKey");

            if (GetPropertyFromAlias("recaptchaEnabled") != "1")
                _recaptchaArea.Visible = false;
        }

        private void SendContactMail()
        {
            var mail = new MailMessage();
            var htmlMail = true;
            if (GetPropertyFromAlias("contactMailHtml") != "1")
                htmlMail = false;

            var mailFrom = _contactName.Text == string.Empty
                ? new MailAddress(HttpUtility.HtmlEncode(_contactEmail.Text))
                : new MailAddress(HttpUtility.HtmlEncode(_contactEmail.Text), HttpUtility.HtmlEncode(_contactName.Text));

            mail.From = mailFrom;
            mail.ReplyTo = mailFrom;

            mail.Body = htmlMail
                ? String.Format("{0}{1}{1}{2} ({3})", ConvertNewlinesToHtmlBreaks(HttpUtility.HtmlEncode(_contactMessage.Text)), "<br />", HttpUtility.HtmlEncode(_contactName.Text), HttpUtility.HtmlEncode(_contactEmail.Text))
                : String.Format("{0}{1}{1}{2} ({3})", HttpUtility.HtmlEncode(_contactMessage.Text), Environment.NewLine, HttpUtility.HtmlEncode(_contactName.Text), HttpUtility.HtmlEncode(_contactEmail.Text));

            mail.To.Add(new MailAddress(GetPropertyFromAlias("contactMailTo")));
            mail.Subject = GetPropertyFromAlias("contactMailSubject");
            mail.IsBodyHtml = htmlMail;

            var client = new SmtpClient { EnableSsl = false };
            if (GetPropertyFromAlias("contactMailSmtpEnableSsl") == "1")
                client.EnableSsl = true;

            client.Send(mail);
        }

        private void DoRedirect()
        {
            Response.Redirect(GetPropertyFromAlias("contactRedirectId") != string.Empty
                                  ? umbraco.library.NiceUrl(Convert.ToInt16(GetPropertyFromAlias("contactRedirectId")))
                                  : "/");
        }

        private static string ConvertNewlinesToHtmlBreaks(string str)
        {
            return str.Replace(Environment.NewLine, "<br />");
        }

        private static string GetPropertyFromAlias(string alias)
        {
            return Node.GetCurrent().GetProperty(alias) != null
                ? Node.GetCurrent().GetProperty(alias).Value
                : string.Empty;
        }
    }
}